package com.zjx.mhxykey;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import java.util.Date;

public class KeepAliveService extends Service {
    private static final String TAG = "KeepAliveService";
    private static final int NOTIFICATION_ID = 12345;
    private static final String CHANNEL_ID = "KeepAliveChannel";

    private boolean isRunning = false;
    private PowerManager.WakeLock wakeLock;
    private Handler handler;
    private Runnable taskRunnable;

    // 在KeepAliveService类中添加
    private CommandReceiver commandReceiver;

    @SuppressLint({"InvalidWakeLockTag", "UnspecifiedRegisterReceiverFlag"})
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service onCreate");

        handler = new Handler(Looper.getMainLooper());

        taskRunnable = new Runnable() {
            @Override
            public void run() {
                // 执行你的后台指令
                executeCommand();

                // 每5分钟执行一次
                handler.postDelayed(this, 3 * 1000);
            }
        };

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

        // 动态注册广播接收器
        commandReceiver = new CommandReceiver();
        IntentFilter filter = new IntentFilter("COMMAND_EXECUTED");
        registerReceiver(commandReceiver, filter);
    }

    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service onStartCommand");

        if (!isRunning) {
            isRunning = true;
            startForeground(NOTIFICATION_ID, createNotification());

            if (wakeLock != null && !wakeLock.isHeld()) {
                wakeLock.acquire();
            }

            handler.post(taskRunnable);
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service onDestroy");

        isRunning = false;

        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
        }

        if (handler != null) {
            handler.removeCallbacks(taskRunnable);
        }

        stopForeground(true);

        // 取消注册广播接收器
        if (commandReceiver != null) {
            unregisterReceiver(commandReceiver);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void executeCommand() {
        // 在这里执行你的后台指令
        Log.d(TAG, "执行后台指令: " + new Date());

        // 示例：发送广播通知指令已执行
        Intent broadcastIntent = new Intent("COMMAND_EXECUTED");
        broadcastIntent.setPackage(getPackageName()); // 限制只发送给本应用
        broadcastIntent.setClass(this, CommandReceiver.class); // 明确指定接收器

        // 对于Android 8.0+，需要设置Component
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            broadcastIntent.setComponent(new ComponentName(this, CommandReceiver.class));
        }

        sendBroadcast(broadcastIntent);
    }

    private Notification createNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "后台服务",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("正在执行后台指令");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("后台指令执行中")
                .setContentText("应用正在后台运行")
                .setSmallIcon(R.drawable.ic_notification)
                .build();
    }
}
